package serialdata

import (
	"encoding/json"
	"errors"
	"fmt"
	"github.com/tarm/serial"
	"net"
	"strconv"
	"time"
)

//@发送到本地串口服务
func SendSerialMsg(frame DataFrame) ([]byte, error) {
	dialer := net.Dialer{Timeout: time.Millisecond * 500}
	conn, err := dialer.Dial("tcp", SerialIP)
	if err != nil {
		return nil, err
	}
	send, err := json.Marshal(&frame)
	if _, err = conn.Write(send); err != nil {
		return nil, err
	}
	var readBuffer = make([]byte, 2048)
	n, err := conn.Read(readBuffer)
	if err != nil {
		return nil, err
	}
	return readBuffer[:n], nil
}

func GetLocalSerialParams(devParams map[string]string) (*serial.Config, error) {
	c := &serial.Config{}
	name, ok := devParams["Name"]
	if !ok {
		fmt.Println("Name err:", devParams["Name"])
		return nil, errors.New("Name err")
	}
	c.Name = name
	baud, ok := devParams["BaudRate"]
	if !ok {
		return nil, errors.New("BaudRate err")
	}
	res, _ := strconv.ParseInt(baud, 10, 0)
	c.Baud = int(res)
	DataBits, ok := devParams["DataBits"]
	if !ok {
		return nil, errors.New("DataBits err")
	}
	res, _ = strconv.ParseInt(DataBits, 10, 0)
	c.Size = byte(res)
	Parity, ok := devParams["Parity"]
	if !ok {
		fmt.Println("Parity err")
		return nil, errors.New("Parity err")
	}
	c.Parity = ParseParity(Parity)
	s, ok := devParams["StopBits"]
	if !ok {
		fmt.Println("StopBits err")
		return nil, errors.New("StopBits err")
	}
	c.StopBits = ParseStopBit(s)
	return c, nil
}
